#include "RobotModel.h"

using namespace Ogre;

RobotModel::RobotModel(Ogre::SceneManager * sm): mSceneMgr(sm),target(Ogre::Vector3(0,0,0)),AnimSpeed(0.3)
{
	Initialization();
}

RobotModel::~RobotModel(void)
{
}

void RobotModel::Initialization()
{
	mRobotEntity = mSceneMgr->createEntity("Robot.mesh");
	mAttachedSceneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
	mAttachedSceneNode->attachObject(mRobotEntity);
	mAttachedSceneNode->setScale(0.1,0.1,0.1);
	this->setSpeed(2);

	RobotStatus = IDLE;
	as = mRobotEntity->getAnimationState("Idle");
	as->setEnabled(true);
	as->setLoop(true);
}

void RobotModel::updateRobot()
{
	if( (getPostion() - target).length() < 100)
	{
		RobotStatus = IDLE;
		as->setEnabled(false);
		as = mRobotEntity->getAnimationState("Idle");
		as->setEnabled(true);
	}

	if(RobotStatus == IDLE)
	{
		setTargetPostion(this->getPostion());
	}
	else if(RobotStatus == MOVING)
	{
/*		int speedX = rand()%501;
		int speedY = Ogre::Math::Sqrt(500 * 500 - speedX * speedX);

		Ogre::Real RealSpeedX;
		Ogre::Real RealSpeedY;

		srand(speedX);
		if(rand()%2 == 0) {
			RealSpeedX = (Ogre::Real)speedX;
		} else {
			RealSpeedX = -(Ogre::Real)speedX;
		}
		srand(speedY);
		if(rand()%2 == 0) {
			RealSpeedY = (Ogre::Real)speedY;
		} else {
			RealSpeedY = -(Ogre::Real)speedY;
		}	*/	
	}
	else if(RobotStatus == SHOOTING)
	{
		setTargetPostion(this->getPostion());
	}

}

void RobotModel::AddTime( Ogre::Real deltaTime )
{
	updateRobot();
	as->addTime(AnimSpeed * deltaTime);
	PapaObject::AddTime(deltaTime);
}

void RobotModel::ChangeStatus()
{
	srand(rand()%100);
	int ch = rand()%100;
	//PRINT("ch: "<<ch);
	if(ch < 50)
	{
		RobotStatus = MOVING;
		as->setEnabled(false);
		as = mRobotEntity->getAnimationState("Walk");
		as->setEnabled(true);

		srand(rand()%100);
		Ogre::Vector3 CurrentPos = this->getPostion();
		Ogre::Vector3 RandomNext = Ogre::Vector3(-1000+rand()%2001, CurrentPos.y, -1000+rand()%2001);
		setTargetPostion(RandomNext);
		PRINT(RandomNext);
		Ogre::Quaternion quat = Ogre::Vector3::UNIT_X.getRotationTo(this->getDirection());
		this->setTargetOrientation(quat,0.1);
	}
	else if(ch > 75)
	{
		RobotStatus = IDLE;
		as->setEnabled(false);
		as = mRobotEntity->getAnimationState("Idle");
		as->setEnabled(true);
	}
	else
	{
		RobotStatus = SHOOTING;
		as->setEnabled(false);
		as = mRobotEntity->getAnimationState("Shoot");
		as->setEnabled(true);

		Ogre::Quaternion quat = Ogre::Vector3::UNIT_X.getRotationTo(this->target - this->getPostion());
		this->setTargetOrientation(quat,2);
	}
}

